package com.zwy.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.args.GeoUnit;
import redis.clients.jedis.params.GeoRadiusParam;
import redis.clients.jedis.resps.GeoRadiusResponse;

import java.util.List;

@Component
public class RedisGeoUtil {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JedisPool jedisPool;

    public void geoadd(int dbIndex, String key, double longitude, double latitude, String member) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            jedis.geoadd(key, longitude, latitude, member);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    public double geodist(int dbIndex, String key, String member1, String member2, GeoUnit unit) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.geodist(key, member1, member2, unit);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    public List<String> geohash(int dbIndex, String key, String... members) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.geohash(key, members);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    public List<GeoCoordinate> geopos(int dbIndex, String key, String... members) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.geopos(key, members);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    public List<GeoRadiusResponse> georadius(int dbIndex, String key, double longitude, double latitude, double radius,
                                          GeoUnit unit, GeoRadiusParam param) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.georadius(key, longitude, latitude, radius, unit, param);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }
}
